package com.fmh.mybatisplus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fmh.mybatisplus.pojo.Menu;
import com.fmh.mybatisplus.pojo.Role;
import com.fmh.mybatisplus.pojo.User;
import com.fmh.mybatisplus.service.MenuService;
import com.fmh.mybatisplus.service.RoleService;
import com.fmh.mybatisplus.service.UserService;
import com.fmh.mybatisplus.mapper.UserMapper;
import com.fmh.mybatisplus.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author 27713
* @description 针对表【sys_user】的数据库操作Service实现
* @createDate 2023-05-11 05:41:05
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Autowired
    RoleService roleService;
    @Autowired
    UserMapper userMapper;
    @Autowired
    MenuService menuService;
    @Autowired
    RedisUtil redisUtil;

    /**
     * 获取用户名
     * @param username
     * @return
     */
    @Override
    public User getByUserName(String username) {
        User one = getOne(new QueryWrapper<User>().eq("username", username));
        return one;
    }

    /**
     * 获取权限
     * @param userId
     * @return
     */
    @Override
    public String getUserAuthorityInfo(Long userId) {

        // 获取用户id
        User user = userMapper.selectById(userId);

        // ROLE_admin,ROLE_normal,sys:user:list,....
        String authority = "";  // 角色，菜单的承载

        // 判断 有缓存则先取，没有再去数据库获取
        if(redisUtil.hasKey("DuckAuthority:" + user.getUsername())) {
            authority = (String) redisUtil.get("DuckAuthority:" + user.getUsername());
        } else {
            // 获取用户角色
            List<Role> roles = roleService.list(new QueryWrapper<Role>().
                    inSql("id", "select role_id from sys_user_role where deleted = 0 and user_id = " + userId));

            if(roles.size() > 0) {
                // 流转换获取角色数据
                String roleCodes = roles.stream().map(r -> "ROLE_" + r.getCode()).collect(Collectors.joining(","));
                authority = roleCodes.concat(",");
            }

            // 菜单操作权限
            List<Long> menuIds = userMapper.getNavMenuIds(userId);

            if(menuIds.size() > 0) {
                List<Menu> menus = menuService.listByIds(menuIds);
                String menusPerms  = menus.stream().map(m -> m.getPerms()).collect(Collectors.joining(","));
                authority = menusPerms.concat(menusPerms);
            }

            // redis缓存（时间一个小时）
            redisUtil.set("DuckAuthority:" + user.getUsername(), authority,  60 * 60);
        }
        return authority;
    }




}




